import config from "@/script/config.js"
import store from "@/store/index.js"

module.exports = {
	/**
	 * 判断字符串是否为空
	 * @param {Object} string [判断字符]
	 */
	isEmptyString: function(string) {
		if (string == undefined ||
			typeof string == "undefined" ||
			!string ||
			string == null ||
			string == '' ||
			/^\s+$/gi.test(string)) {
			return true;
		} else {
			return false;
		}
	},

	// 滚动到底部（优化版本，避免频繁调用）
	_lastToBottomAt: 0,
	toBottom(time = 50, force = false) {
		const now = Date.now();
		if (!force && now - this._lastToBottomAt < 200) {
			return;
		}
		this._lastToBottomAt = now;
		
		// 使用store中的scrollTop状态
		store.commit('app/setScrollTop', -1);
		setTimeout(() => {
			store.commit('app/setScrollTop', 999999);
		}, time);
	},

	// 初始化用户信息
	initSetInfo: function(data) {
		store.commit("setUser", data?.myInfo || data);
		if (data?.token) {
			uni.setStorageSync("token", data.token);
		}
		if (data?.jwt) {
			uni.setStorageSync("jwt", data.jwt);
		}
	},

	// 用户登出
	logout() {
		uni.removeStorageSync("token");
		uni.removeStorageSync("jwt");
		uni.removeStorageSync("sender");
		store.dispatch('logout');
	},

	// 检查是否已登录
	isLogin() {
		const token = uni.getStorageSync("token");
		const jwt = uni.getStorageSync("jwt");
		const sender = uni.getStorageSync("sender");
		return (token || jwt) && sender;
	},

	/**
	 * 判断是否为手机号
	 * @param {Object} phone [手机号]
	 */
	isPoneAvailable: function(phone) {
		var myreg = /^[1][0-9]{10}$/;
		if (!myreg.test(phone)) {
			return false;
		} else {
			return true;
		}
	},

	/**
	 * 判断是否为身份证号
	 * @param {Object} sId [身份证]
	 */
	isCardID: function(sId) {
		var iSum = 0;
		if (!/^\d{17}(\d|X)$/i.test(sId)) return "你输入的身份证长度或格式错误";
		sId = sId.replace(/X$/i, "a");
		let sBirthday = sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2));
		var d = new Date(sBirthday.replace(/-/g, "/"));
		if (sBirthday != (d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate())) return "您输入的身份证号非法";
		for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
		if (iSum % 11 != 1) return "您输入的身份证号非法";
		return true;
	},

	/**
	 * 判断今天是否为本月最后一天
	 */
	isLastDayOfMonth: function() {
		var flag = false;
		var date = new Date();
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var today = date.getDate();

		var new_year = year;
		var new_month = month + 1;
		if (new_month > 12) {
			new_month = 1;
			new_year++;
		}
		var new_date = new Date(new_year, new_month - 1, 1);
		var month_last_day = (new Date(new_date.getTime() - 1000 * 60 * 60 * 24)).getDate();

		if (today == month_last_day) {
			flag = true;
		}
		return flag;
	},

	/**
	 * 截取特定url参数
	 * @param {Object} name [参数名称]
	 */
	getQueryString: function(name) {
		var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		var r = window.location.search.substr(1).match(reg);
		if (r != null) {
			return unescape(r[2]);
		}
		return null;
	},

	// 统一的消息提示
	tipMsg: function(title, icon, time, mask) {
		title = title == undefined ? "系统繁忙" : title;
		icon = icon == undefined ? "none" : icon;
		time = time == undefined ? 1500 : time;
		mask = mask == undefined ? true : mask;
		uni.showToast({
			title: title,
			icon: icon,
			mask: mask,
			duration: time
		})
	},

	// 成功提示
	showSuccess: function(message) {
		uni.showToast({
			title: message || '操作成功',
			icon: 'success'
		});
	},

	// 错误提示
	showError: function(message) {
		uni.showToast({
			title: message || '操作失败',
			icon: 'none'
		});
	},

	// 加载提示
	showLoading: function(message) {
		uni.showLoading({
			title: message || '加载中...',
			mask: true
		});
	},

	// 隐藏加载
	hideLoading: function() {
		uni.hideLoading();
	},

	/** 
	 * 页面跳转 - navigateTo
	 * @param {string} url 目标页面的路由
	 * @param {Object} param 传递给目标页面的参数
	 */
	navigateTo(url, param = {}, flag) {
		if (!this.isLogin() && !flag) {
			this.loginTip();
			return;
		}
		
		let part = '';
		for (var item in param) {
			part += '&' + item + '=' + encodeURIComponent(param[item]);
		}
		url = "/pages" + url + part.replace('&', '?');
		
		uni.navigateTo({
			url: url,
			fail: err => {
				console.error('页面跳转失败:', err);
				this.tipMsg('页面跳转失败');
			}
		});
	},

	/** 
	 * 页面返回 - navigateBack
	 * @param {number} delta 返回的页面数
	 */
	navigateBack(delta = 1) {
		uni.navigateBack({
			delta: delta,
			fail: err => {
				console.error('页面返回失败:', err);
				// 如果返回失败，跳转到首页
				this.reLaunch('/consultation/consultation');
			}
		});
	},

	// Tab页面切换
	switchTab(url) {
		uni.switchTab({
			url: url,
			fail: err => {
				console.error('Tab切换失败:', err);
				this.tipMsg('页面切换失败');
			}
		});
	},

	// 页面重定向
	redirectTo(url, param = {}, flag) {
		if (!this.isLogin() && !flag) {
			this.loginTip();
			return;
		}
		
		let part = '';
		for (var item in param) {
			part += '&' + item + '=' + encodeURIComponent(param[item]);
		}
		url = "/pages" + url + part.replace('&', '?');
		
		uni.redirectTo({
			url: url,
			fail: err => {
				console.error('页面重定向失败:', err);
				this.tipMsg('页面跳转失败');
			}
		});
	},

	// 重新启动应用
	reLaunch(url, param = {}) {
		let part = '';
		for (var item in param) {
			part += '&' + item + '=' + encodeURIComponent(param[item]);
		}
		
		// 处理URL格式，确保正确的路径
		let finalUrl = url;
		if (!url.startsWith('/')) {
			finalUrl = '/' + url;
		}
		if (!url.startsWith('/pages/') && !url.startsWith('/')) {
			finalUrl = "/pages/" + url;
		}
		
		finalUrl = finalUrl + (part ? part.replace('&', '?') : '');
		
		console.log('准备跳转到:', finalUrl);
		
		uni.reLaunch({
			url: finalUrl,
			success: () => {
				console.log('页面跳转成功:', finalUrl);
			},
			fail: err => {
				console.error('应用重启失败:', err, finalUrl);
				// 降级处理
				uni.navigateTo({
					url: finalUrl,
					fail: (navErr) => {
						console.error('降级跳转也失败:', navErr);
						this.tipMsg('页面跳转失败');
					}
				});
			}
		});
	},

	// 登录提示
	loginTip() {
		// 检查当前是否已经在登录页面，避免重复提示
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		if (currentPage && currentPage.route.includes('index/index')) {
			return; // 如果已经在登录页面，不显示提示
		}
		
		uni.showModal({
			title: '提示',
			content: '请先登录',
			confirmText: '去登录',
			success: (res) => {
				if (res.confirm) {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			}
		});
	},

	// 获取设备信息
	getSystemInfo() {
		return new Promise((resolve, reject) => {
			const cachedInfo = uni.getStorageSync("systemInfo");
			if (cachedInfo) {
				resolve(cachedInfo);
				return;
			}

			uni.getSystemInfo({
				success: info => {
					// 缓存系统信息
					uni.setStorageSync("systemInfo", info);
					resolve(info);
				},
				fail: err => {
					reject(err);
				}
			});
		});
	},

	// 格式化时间
	formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
		if (!date) return '';
		
		const d = new Date(date);
		const year = d.getFullYear();
		const month = String(d.getMonth() + 1).padStart(2, '0');
		const day = String(d.getDate()).padStart(2, '0');
		const hour = String(d.getHours()).padStart(2, '0');
		const minute = String(d.getMinutes()).padStart(2, '0');
		const second = String(d.getSeconds()).padStart(2, '0');
		
		return format
			.replace('YYYY', year)
			.replace('MM', month)
			.replace('DD', day)
			.replace('HH', hour)
			.replace('mm', minute)
			.replace('ss', second);
	},

	// 防抖函数
	debounce(func, wait) {
		let timeout;
		return function executedFunction(...args) {
			const later = () => {
				clearTimeout(timeout);
				func(...args);
			};
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
		};
	},

	// 节流函数
	throttle(func, limit) {
		let inThrottle;
		return function() {
			const args = arguments;
			const context = this;
			if (!inThrottle) {
				func.apply(context, args);
				inThrottle = true;
				setTimeout(() => inThrottle = false, limit);
			}
		}
	}
}